﻿using System;
using System.Collections.Generic;
using System.Text;
using PCDoctor.Utils;
using System.Net;

namespace PCDoctor.Licensing
{
    /// <summary>
    /// Класс для работы с системой лицензирования, Singleton
    /// </summary>
    class LicenseWorker
    {
        protected static LicenseWorker worker = null;

        public static LicenseWorker getInstance()
        {
            if (worker == null)
            {
                worker = new LicenseWorker();
            }
            return worker;
        }

        public LicenseWorker()
        {
            RegistrationChecked = false;
            CheckRegisteration();
        }

        /// <summary>
        /// Проверяет валидность ключа
        /// </summary>
        /// <returns>bool</returns>
        public bool CheckRegisteration()
        {
            if (RegistrationChecked)
            {
                return isRegistered;
            }
            bool result = false;
            Config cfg = Config.getInstance();
            if (cfg.getValue(Config.REGISTRATION_CODE) == "")
            {
                SetDemoMode();
                RegistrationChecked = true;
            }
            else
            {
                ValidateKey();
            }
            return result;
        }

        protected bool _isRegistered = false;

        /// <summary>
        /// Зарегистрирована ли программа
        /// </summary>
        public bool isRegistered
        { 
            get
            {
                if (!RegistrationChecked)
                {
                    CheckRegisteration();
                }
                return _isRegistered;
            }
            private set
            {
                _isRegistered = value;
            }
        }

        /// <summary>
        /// Была ли проведена проверка валидности ключа
        /// </summary>
        protected bool RegistrationChecked { get; set; }

        public void ValidateKey()
        {
            try
            {
                WebClient c = new WebClient();
                string licenseData = c.DownloadString(Config.LICENSE_CHECK_URL +
                    "?key=" + Config.getInstance().getValue(Config.REGISTRATION_CODE));
                RegistrationChecked = true;
                if (licenseData == "true")
                {
                    isRegistered = true;
                }
            }
            catch (Exception e)
            {
                ErrorHandler.HandleError(e.Message);
                isRegistered = false;
                RegistrationChecked = false;
            }
        }

        /// <summary>
        /// Активация программы на сервере
        /// </summary>
        /// <param name="key">Ключ активации</param>
        /// <returns>
        ///     0, если все ОК,
        ///     больше 0 если ключ неверный,
        ///     меньше 0 если ошибка запроса
        /// </returns>
        public int RegisterProgram(string key)
        {
            int result = 0;
            try
            {
                WebClient c = new WebClient();
                string response = c.DownloadString(Config.ACTIVATION_URL +
                    "?key=" + key);
                if (response != "true")
                {
                    result = 10;
                }
                else
                {
                    Config cfg = Config.getInstance();
                    cfg.setValue(Config.REGISTRATION_CODE, key);
                    cfg.setValue(Config.REGISTRATION_STATUS, "1");
                    cfg.Save();
                }
            }
            catch (Exception e)
            {
                ErrorHandler.HandleError(e.Message);
                result = -10;
            }
            return result;
        }

        public void SetDemoMode()
        {
            Config cfg = Config.getInstance();
            cfg.setValue(Config.REGISTRATION_CODE, Config.DEMO_REG_CODE);
            cfg.setValue(Config.REGISTRATION_STATUS, "0");
            cfg.Save();
        }
    }
}
